package com.wpzf.ndhc.controller;


import com.wpzf.common.core.utils.ServletUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.common.log.annotation.Log;
import com.wpzf.common.log.enums.BusinessType;
import com.wpzf.common.security.service.TokenService;
import com.wpzf.common.security.utils.SecurityUtils;
import com.wpzf.ndhc.domain.*;
import com.wpzf.ndhc.mapper.WpzfNdhcSqthMapper;
import com.wpzf.ndhc.service.WpzfNdhcSqthService;
import com.wpzf.ndhc.service.WpzfNdhcThshService;
import com.wpzf.system.api.model.LoginUser;
import com.wpzf.zxhc.domain.WpCjDkpw2023DTO;
import com.wpzf.zxhc.domain.WpCjdataUploadDTO;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.TransactionAnnotationParser;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;

@RestController
@RequestMapping("/wpzfndhthsh")
public class WpzfNdhcThshController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WpzfNdhcThshService wpzfNdhcThshService;

    @Autowired
    private WpzfNdhcSqthService wpzfNdhcSqthService;

    //获取已填报批次号
    @RequestMapping(value = "/getPch", method = RequestMethod.POST)
    public AjaxResult getPch(@RequestBody Map<String, Object> param) {
        try {
            List<Map<String, Object>> list = wpzfNdhcThshService.getPch(param);
            return AjaxResult.success("获取成功", list);
        } catch (Exception ex) {
            return AjaxResult.error("获取失败", ex.toString());
        }
    }

    //根据用户所在行政区查询所有已经提交到国家级节点的地块
    @RequestMapping(value = "/getDkList", method = RequestMethod.POST)
    public AjaxResult getDkList(@RequestBody Map<String, Object> param) {
        try {
            List<Map<String, Object>> list = wpzfNdhcThshService.getDkList(param);
            Integer cnt = wpzfNdhcThshService.getDkListCount(param);
            return AjaxResult.success("获取成功", list, cnt);
        } catch (Exception ex) {
            return AjaxResult.error("获取失败", ex.toString());
        }
    }

    //市级地块审核详情
    @RequestMapping(value = "/getThshTaskInfo", method = RequestMethod.POST)
    public AjaxResult getThshTaskInfo(@RequestBody Map<String, Object> param) {
        String jcbh = param.get("jcbh") + "";
        param.put("tbbh", param.get("dkbh"));
        if (jcbh.indexOf(",") != -1) {
            param.put("jcbh", jcbh.split("-")[0]);
        }
        try {
            WpCjTGjjth wpcjTbBaseinfosjDTO = new WpCjTGjjth();
            List<WpCjDkpw2023DTO> lists = new ArrayList<>();
            //获取地块信息  dkxxbxj2023DTOS
            WpCjDkxxbxjNdDTO wpcjDkxxb2023DTO = wpzfNdhcThshService.getDkInfoByDkbh(param);
            wpcjTbBaseinfosjDTO.setWpCjDkxxbxjNdDTO(wpcjDkxxb2023DTO);

            //获取图斑信息 相关图斑全部查出
            List<WpCjTbxxbxjNdDTO> wpCjTbxxb2023DTOS = wpzfNdhcThshService.getTbxxbxjByJcbhList(param);
            wpcjTbBaseinfosjDTO.setWpCjTbxxbxjNdDTOList(wpCjTbxxb2023DTOS);


            //其他相关的拆分图斑
            List<WpCjDkxxbxjNdDTO> wpCjDkxxb2023relatedto = wpzfNdhcThshService.queryWpCjDkInfoByJcbh(param);
            wpcjTbBaseinfosjDTO.setWpCjDkxxbxjNdDTOList(wpCjDkxxb2023relatedto);


            //获取举证照片
            WpCjTbxxbxjNdDTO WpCjTbxxbxjNdDTO = wpzfNdhcSqthService.querytbxxNdByjcbh(param);
            ModelMap modelMap = new ModelMap();
            if (WpCjTbxxbxjNdDTO != null) {
                param.put("sfzz", "自主提取".equals(WpCjTbxxbxjNdDTO.getGjxfhzztq()) ? "1" : "0");
                WpCjGsinfolyNdDTO gsinfoly = wpzfNdhcSqthService.getGsinfoly(param);
                wpcjTbBaseinfosjDTO.setWpCjGsinfolyNdDTO(gsinfoly);
                if ("0".equals(gsinfoly.getInfoly())) {
                    modelMap = wpzfNdhcSqthService.getShowImgsnew(param);
                } else if ("1".equals(gsinfoly.getInfoly())) {
                    List<String> list = new ArrayList<>();
                    list.add(wpzfNdhcSqthService.getInfo(param));
                    modelMap.put("data", list);
                }
            } else {
                modelMap = wpzfNdhcSqthService.getShowImgs(param);
            }

            wpcjTbBaseinfosjDTO.setModelMap(modelMap);

            //图斑截图
            List<WpCjTbjtNdDTO> wpCjTbjt2023DTOS = wpzfNdhcSqthService.querytbjtBytbbh(param);
            wpcjTbBaseinfosjDTO.setWpCjTbjtNdDTOList(wpCjTbjt2023DTOS);

            //获取市级审核信息
            WpCjTbhcjgshijNdDTO wpCjTbhcjgshijNdDTO = wpzfNdhcSqthService.queryTbhcjgshijBytbbh(param);
            wpcjTbBaseinfosjDTO.setWpCjTbhcjgshijNdDTO(wpCjTbhcjgshijNdDTO);

            //获取省级审核信息
            WpCjTbhcjgsjNdDTO wpCjTbhcjgsjNdDTO = wpzfNdhcSqthService.queryTbhcjgsjBytbbh(param);
            wpcjTbBaseinfosjDTO.setWpCjTbhcjgsjNdDTO(wpCjTbhcjgsjNdDTO);

            WpCjGjjThDkNdDTO wpCjGjjThDkNdDTO = wpzfNdhcSqthService.queryGjjThDkByTbbh(param);
            wpcjTbBaseinfosjDTO.setWpCjGjjThDkNdDTO(wpCjGjjThDkNdDTO);

            return AjaxResult.success("获取成功", wpcjTbBaseinfosjDTO);
        } catch (Exception ex) {
            return AjaxResult.error("获取失败", ex.toString());
        }
    }

    //
    @RequestMapping(value = "/thshSubmit", method = RequestMethod.POST)
    public AjaxResult thshSubmit(@RequestBody Map<String, Object> param) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            param.put("shr", loginUser.getSysUser().getNickName());
            param.put("shrxm", loginUser.getUsername());
            Integer rest = wpzfNdhcThshService.thshSubmit(param);
            return AjaxResult.success("获取成功", rest);
        } catch (Exception ex) {
            return AjaxResult.error("获取失败", ex.toString());
        }
    }

    /*数据导入*/
    @Transactional
    @RequestMapping(value = "/uploadExecl", method = RequestMethod.POST)
    public AjaxResult uploadExecl(MultipartFile file, String year) {
        try {
            //获得文件名称
            String fileName = file.getOriginalFilename();

            //获得文件后缀名
            String type = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

            //判断上传的是否是压缩包
            if (!type.equals("xlsx") && !type.equals("xls")) {
                return AjaxResult.error("请上传Execl文件");
            }

            List<Map<String,Object>> list = new ArrayList<>();

            InputStream inputStream = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(inputStream);

            Sheet sheet = workbook.getSheetAt(0);

            // 遍历行，跳过第一行（标题行）
            boolean isFirstRow = true;
            for (Row row : sheet) {
                if (isFirstRow) {
                    isFirstRow = false;
                    continue;
                }

                // 创建一个新的 GjjThDk 实例
                Map<String,Object> map = new HashMap<>();

                // 将 Excel 每列的数据放入实体类相应的字段
                map.put("tbbh",getCellValueAsString(row.getCell(0)));
                map.put("dkbh",getCellValueAsString(row.getCell(0)));
                map.put("pch",getCellValueAsString(row.getCell(1)));
                map.put("xzqdm",getCellValueAsString(row.getCell(2)));
                map.put("sqr",getCellValueAsString(row.getCell(3)));
                map.put("sqrxm",getCellValueAsString(row.getCell(4)));
                map.put("sqthyy",getCellValueAsString(row.getCell(5)));
                map.put("sqsj",getCellValueAsString(row.getCell(6)));
                map.put("pt","0");
                map.put("shr",getCellValueAsString(row.getCell(7)));
                map.put("shrxm",getCellValueAsString(row.getCell(8)));
                map.put("shyj",getCellValueAsString(row.getCell(9)));
                map.put("shyjsm",getCellValueAsString(row.getCell(10)));
                map.put("shsj",getCellValueAsString(row.getCell(11)));
                map.put("status","0");

                map.put("year",year);

                // 将实体对象加入列表
                list.add(map);
            }

            Integer rest = 0;
            for (Map<String, Object> m : list) {
                wpzfNdhcThshService.deleteGJJDK(m);
                wpzfNdhcThshService.deleteFjinfo(m);
                wpzfNdhcThshService.updateThDkStatusByDkbh(m);
                rest += wpzfNdhcThshService.saveGjjThDk(m);
            }
            if (rest>0) {
                return AjaxResult.success("数据导入成功");
            }
        } catch (Exception ex) {
            TransactionAspectSupport.currentTransactionStatus();
            return AjaxResult.error("数据导入失败", ex.toString());
        }
        return AjaxResult.error("数据导入失败");
    }

    // 辅助方法：将单元格值转换为字符串
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }


}
